package cn.neusoft.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {

    private static DruidDataSource dataSource;

    static {
        /*
        通过类加载器读取类路径下的文件jdbc.properties
        项目编译时将resources中的配置文件放入了classes类路径下
         */
        InputStream stream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");

        //创建属性集对象  和xxx.properties配置文件搭配使用
        Properties properties = new Properties();
        try {
            //将xxx.properties属性集文件中的kv对载入到属性集对象中  属性集本身就是一个map结构
            properties.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(properties);

        String driver = properties.getProperty("driver");
        System.out.println(driver);

        dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driver"));
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("Username"));
        dataSource.setPassword(properties.getProperty("Password"));

    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static Connection getConn() throws SQLException {
        return dataSource.getConnection();
    }

    public static QueryRunner getQueryRunner(){
        return new QueryRunner(dataSource);
    }


}
